package com.zhima.service.impl;

import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.zhima.config.AliyunSmsConfiguration;
import com.zhima.exception.ZhimaOjException;
import com.zhima.properties.AliyunSmsProperties;
import com.zhima.service.PhoneService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.zhima.exception.ErrorCode.CHECK_CODE_SEND_FAILURE;

@Slf4j
@Service
public class PhoneServiceImpl implements PhoneService {

    @Autowired
    private AliyunSmsConfiguration aliyunSmsConfiguration;
    @Autowired
    private AliyunSmsProperties aliyunSmsProperties;

    @Override
    public SendSmsResponse send(String phone, String templateParam, String templateCode) {
        // 获取短信发送服务机
        IAcsClient acsClient = aliyunSmsConfiguration.getClient();
        //获取短信请求
        SendSmsRequest request = getSmsRequest(phone, templateParam, templateCode);
        try {
            return acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            log.error("发送短信发生错误。错误代码是 [{}]，错误消息是 [{}]，错误请求ID是 [{}]，错误Msg是 [{}]，错误类型是 [{}]",
                    e.getErrCode(),
                    e.getMessage(),
                    e.getRequestId(),
                    e.getErrMsg(),
                    e.getErrorType());
            throw new ZhimaOjException(e, CHECK_CODE_SEND_FAILURE);
        }
    }

    private SendSmsRequest getSmsRequest(String phone, String templateParam, String templateCode) {
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setSignName(aliyunSmsProperties.getSignName());
        request.setTemplateCode(templateCode);
        request.setTemplateParam(templateParam);
        // 这个可以用来拓展，暂时用不到
        // request.setOutId();
        return request;
    }
}
